<!--
 * @description  :  poi 信息
 * @descriptionDetail:  poi 信息
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-10-26 09:43:02
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
    </theme-navbar>
    <!-- #endif -->

    <view class="content u-page">
      <u-form
        label-width="auto"
        :model="formData"
        label-position="top"
        :error-type="['message','border-bottom']"
        ref="form"
      >
        <u-form-item prop="gisName" :required="true" label="名称:">
          <u-input placeholder="请输入" type="text" v-model="formData.gisName"></u-input>
        </u-form-item>
        <u-form-item
          prop="gisSubtype"
          :right-icon="from == 1 ? '' : 'arrow-right'"
          :required="true"
          label="分类:"
        >
          <u-input
            :disabled="true"
            placeholder="请选择"
            type="text"
            :needValid="true"
            v-model="formData.gisSubtypeName"
            @click="selectType"
          ></u-input>
        </u-form-item>
        <u-form-item
          prop="ownAreaOrgUuid"
          :right-icon="from == 1 ? '':'arrow-right'"
          :required="true"
          label="选择片区:"
          v-if="areaType == 1"
        >
          <u-input
            placeholder="请选择"
            type="text"
            :disabled="true"
            :needValid="true"
            v-model="formData.ownAreaOrgName"
            @click="chooseOrg"
          ></u-input>
        </u-form-item>

        <u-form-item
          prop="curOrgUuid"
          right-icon="arrow-right"
          :right-icon-style="{fontSize: '40rpx'}"
          :required="true"
          label="专卖管理所:"
          v-if="areaType == 2"
        >
          <u-input
            placeholder="请选择"
            type="text"
            :disabled="true"
            :needValid="true"
            v-model="formData.curOrgName"
            @click="chooseOrgGls"
          ></u-input>
        </u-form-item>
        <u-form-item prop="latitude" label="地图坐标:">
          {{ lnglat }}
        </u-form-item>
        <u-form-item label="关联当前零售户" label-position="left" v-if="from == 1">
          <view class="market_cs">
            <u-switch :disabled="true" v-model="formData.relatveLic"></u-switch>
          </view>
        </u-form-item>
        <u-form-item prop="retailDistance" :required="distanceRequire" label="距离零售户(米):" v-if="from == 1">
          <view style="display: flex;flex-direction: column;width: 100%;">
            <view style="margin-bottom: 10rpx;font-size: 22rpx;color: #fa3534;">
              默认计算经纬度两点直线距离,可自行修改
            </view>
            <u-input placeholder="请输入..." type="number" v-model="formData.retailDistance"></u-input>
          </view>
        </u-form-item>
        <u-form-item prop="gisDesc" label="描述:">
          <u-input placeholder="请输入..." type="textarea" v-model="formData.gisDesc"></u-input>
        </u-form-item>
      </u-form>
    </view>
    <view class="submit-btns btn-other-cls">
      <u-button class="u-btn" type="primary" @click="confirm">
        提交
      </u-button>
    </view>
    <!-- 组织机构选择 -->
    <u-popup mode="bottom" height="80%" v-model="orgSelectShow" @close="handlerCloseOrg">
      <org-select :tips="tips" :limitNodeType="limitNodeType" :treeType="treeType" @choose="handlerChooseOrg"></org-select>
    </u-popup>
    <!-- 分类选择 -->
    <u-popup mode="bottom" height="80%" v-model="typeTreeShow" @close="handlerCloseOrg">
      <type-tree @choose="handlerChooseType"></type-tree>
    </u-popup>
  </view>
</template>

<script>
import {
  AMapMixin,
} from '@/common/AMapMixin.js';
import OrgSelect from "@/components/org-select";
import typeTree from "./typeTree.vue"
import zjCommonService from "@/service/common/common.service";
import {M_GIS_TYPE_TREE,} from "@/service/check/mapping/enum.js";
export default {
  components: {
    OrgSelect, typeTree,
  },
  mixins: [AMapMixin,],
  onLoad(opt) {
    this.from = opt.from || 0;
    this.fromItemType = opt.fromItemType || '';
    this.relatveLic = opt.relatveLic == 'true';
    let p = this.getRouteParam() || {};
    this.marketGis = this.$u.deepClone(p);
    if (this.marketGis) {
      this.formData.gisName = this.marketGis.gisName;
      this.formData.latitude = this.marketGis.latitude;
      this.formData.longitude = this.marketGis.longitude;
      this.formData.gisDesc = this.marketGis.gisDesc;
      this.formData.curOrgUuid = this.marketGis.curOrgUuid;
      this.formData.curOrgName = this.marketGis.curOrgName;
      this.formData.ownAreaOrgUuid = this.marketGis.ownAreaOrgUuid;
      this.formData.ownAreaOrgName = this.marketGis.ownAreaOrgName;
      this.formData.gisSubtype = this.marketGis.gisSubtype;
      this.formData.gisType = this.marketGis.gisType;
      this.formData.gisSubtypeName = this.marketGis.gisSubtypeName;
      this.formData.retailDistance = this.marketGis.retailDistance;
    } else {
      this.marketGis = undefined;
    }
    if(this.from == 1){
      this.formData.ownAreaOrgUuid = opt.ownAreaOrgUuid || "";
      this.formData.ownAreaOrgName = opt.ownAreaOrgName || "";
      this.retailerPos = [opt.longitude, opt.latitude,];
      this.formData.relatveLic = true;
    }
  },
  data() {
    return {
      areaType: 0, // 1 周边环境 2 烟草部门
      from: 0, //  0 表示采集入口  1 表示检查关联入口
      fromItemType: '', // 来源的分类
      retailerPos: [],
      relatveLic: false, // 是否已关联
      formData: {
        gisName: "",
        latitude: "",
        longitude: "",
        gisDesc: "",
        curOrgUuid: "",
        curOrgName: "",
        ownAreaOrgUuid: "",
        ownAreaOrgName: "",
        gisSubtype: "",
        gisSubtypeName: "",
        relatveLic:false,
        retailDistance:'',
      },
      marketGis: undefined,
      orgSelectShow: false,
      treeData: undefined,
      treeType: "zm-pq",
      limitNodeType: "07",
      typeTreeShow: false,
      tips:"",
      keys:['gisName','latitude','longitude','gisDesc','curOrgUuid','curOrgName','ownAreaOrgUuid','ownAreaOrgName','gisSubtype','gisSubtypeName','relatveLic','gisType',],
      rules: {
        gisName: [{
          required: true,
          message: '请输入名称',
          trigger: ['blur', 'change',],
        },],
        gisSubtype: [{
          required: true,
          message: '请选择分类',
          trigger: ['blur', 'change',],
        },],
        ownAreaOrgUuid: [{
          required: true,
          message: '请选择片区',
          trigger: ['blur', 'change',],
        },],
        curOrgUuid: [{
          required: true,
          message: '请选择专卖管理所',
          trigger: ['blur', 'change',],
        },],
        retailDistance:[{
          // 自定义验证函数，见上说明
          validator: (rule, value, callback) => {
            if(this.distanceRequire){
              return !this.$u.test.isEmpty(value);
            }else{
              return true;
            }
          },
          message: '请输入距离',
          // 触发器可以同时用blur和change
          trigger: ['change','blur',],
        },],
      },
    }
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.form.setRules(this.rules);
  },
  computed: {
    lnglat() {
      if (this.$u.test.isEmpty(this.formData.latitude)) {
        return "";
      }
      return this.formData.longitude + "," + this.formData.latitude;
    },
    distanceRequire(){
      if(this.from != 1) return false;
      return this.formData.gisSubtype == M_GIS_TYPE_TREE.GIS_TYPE1 || this.formData.gisSubtype == M_GIS_TYPE_TREE.GIS_TYPE2;
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    initAmap() {
      if(this.from == 1){
        this.formData.retailDistance = Number(AMap.GeometryUtil.distance(this.retailerPos, [this.formData.longitude ,  this.formData.latitude,])).toFixed(2);
      }
    },
    init() {
      let self = this;
      if(this.from == 1){
        this.initOrgPicker(this.fromItemType);
        zjCommonService.gisTypeTree().then(dr => {
          self.treeData = dr.data;
          this.getFromItemTypeName();
        });
      }else{
        this.initOrgPicker(this.marketGis.gisSubtype);
      }
    },
    getTreeTypeArr(arr, children){
      for (let i = 0; i < children.length; i++) {
        arr.push(children[i]);
        if(children[i].children){
          this.getTreeTypeArr(arr,children[i].children);
        }
      }
    },
    getFromItemTypeName(){
      let arr = [];
      this.getTreeTypeArr(arr, this.treeData);
      let ap = arr.filter(itp => {
        return itp.val == this.fromItemType;
      });
      if(ap.length > 0){
        this.formData.gisSubtype = ap[0].val;
        this.formData.gisSubtypeName = ap[0].txt;
        this.formData.gisType = ap[0].pCode || "";
      }
    },
    confirm() {
      let self = this;
      this.$refs['form'].validate(valid => {
        if (valid) {
          for (let k = 0 ; k < self.keys.length; k++) {
            this.$set(this.marketGis, this.keys[k], this.formData[this.keys[k]]);
          }
          self.$modal.showLoading('正在提交...');
          let isAdd = !self.marketGis.gisUuid;
          let promise = !self.marketGis.gisUuid ? zjCommonService.saveLocation(self.marketGis) :
            zjCommonService.modifyLocation(self.marketGis);
          promise.then(dr => {
            self.$modal.hideLoading();
            if (dr.success) {
              self.marketGis = dr.bean;
              if(self.from == 1){ //
                if(self.relatveLic){ // 原始是关联状态
                  self.backPrev({
                    paramKey: "updLic",
                    param: self.marketGis,
                  });
                }else if(self.formData.relatveLic){ // 需要关联
                  self.marketGis.retailDistance = self.formData.retailDistance;
                  self.backPrev({
                    paramKey: "relatveLic",
                    param: self.marketGis,
                  });
                }else{ // 不需要关联
                  self.backPrev({
                    paramKey: "addUnLic",
                    param: self.marketGis,
                  });
                }
              }else{
                self.backPrev({
                  paramKey: "collectInfo",
                  param: self.marketGis,
                });
              }
            } else {
              self.$modal.alert('提交失败:' + dr.msg);
            }
          }).catch(err => {
            self.$modal.hideLoading();
            self.$modal.alert('提交异常');
          });
        }
      });
    },
    // 选中分类类型回调
    handlerChooseType(sItems) {
      if(this.from == 1) return;
      if (sItems && sItems.length > 0) {
        this.initOrgPicker(sItems[0].val);
        this.formData.gisSubtype = sItems[0].val;
        this.formData.gisSubtypeName = sItems[0].txt;
        this.formData.gisType = sItems[0].pCode || "";
      }
      this.typeTreeShow = false;
    },
    // 选择分类
    selectType() {
      if(this.from == 1) return;
      this.typeTreeShow = true;
    },
    /**
			 * 初始化专卖管理所、片区选择
			 * @param gisType
			 */
    initOrgPicker(gisType) {
      if (!gisType) {
        return;
      }
      // 如果选中了“周边环境”，则需要选择片区
      if (gisType.startsWith("01")) {
        this.areaType = 1;
        this.formData.curOrgName = "";
        this.formData.curOrgUuid = "";
      } else if (gisType == "0201") { // 选中了烟草部门，显示专卖管理所
        this.areaType = 2;
        this.formData.ownAreaOrgName = "";
        this.formData.ownAreaOrgUuid = "";
      } else {
        this.areaType = 0;
        this.formData.curOrgName = "";
        this.formData.curOrgUuid = "";
        this.formData.ownAreaOrgName = "";
        this.formData.ownAreaOrgUuid = "";
      }
    },
    /**
			 * 选择片区
			 */
    chooseOrg() {
      if(this.from == 1) return;
      this.treeType = "zm-pq";
      this.tips = "请选择片区";
      this.limitNodeType = "07";
      this.orgSelectShow = true;
    },

    /**
	 * 选择专卖管理所
	 */
    chooseOrgGls() {
      this.treeType = "zm-gls";
      this.tips = "请选择专卖管理所";
      this.limitNodeType = "06";
      this.orgSelectShow = true;
    },
    handlerChooseOrg(orgs) {
      let org = orgs[0];
      if (this.treeType == "zm-gls") {
        if (org == undefined) {
          this.$modal.alert("请选择专卖管理所");
          return;
        }
        this.formData.curOrgName = org.name;
        this.formData.curOrgUuid = org.id;
      } else if (this.treeType == "zm-pq") {
        if (org == undefined) {
          this.$modal.alert("请选择片区");
          return;
        }
        this.formData.ownAreaOrgName = org.name;
        this.formData.ownAreaOrgUuid = org.id;
      }
      this.orgSelectShow = false;
    },
    handlerCloseOrg() {},
  },
}
</script>

<style scoped lang="scss">
	.page{
		padding: 0;
	}
	.content {
		padding: $cm-conent-padding-column $cm-content-paddng-row;
	}
.market_cs {
	width: 100%;
	display: flex;
	flex-direction: row;
	justify-content: flex-end;
}
</style>
